﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Jayden.Dll.Web.HtmlControls;
using Jayden.Dll.Web;

namespace Jayden.Site.PopjesInDeZak.Dll
{
	public class CartDiv : Div
	{
		private Table m_Invoice;
		private TBody m_InvoiceLines;
		private Td m_ShippingPrice;
		private Td m_TotalPrice;
		private P m_Warning;
		private Span m_ItemCount;
		private Div m_Summary;

		public override void Load(System.Xml.XmlNode node, Jayden.Dll.Web.HtmlControlLoader loader)
		{
			base.Load(node, loader);
			m_Summary = GetElementByServerId<Div>("summary", true);
			m_ItemCount = GetElementByServerId<Span>("itemCount", true);
			m_Invoice = GetElementByServerId<Table>("invoice", true);
			m_InvoiceLines = GetElementByServerId<TBody>("invoiceLines", true);
			m_ShippingPrice = GetElementByServerId<Td>("shippingPrice", true);
			m_TotalPrice = GetElementByServerId<Td>("totalPrice", true);
			m_Warning = GetElementByServerId<P>("warning", true);
		}

		public PopjesInDeZakPageHtml Page { get { return Root as PopjesInDeZakPageHtml; } }

		public Tr CreateCartLine(CartSessionLine line, int index)
		{
			Tr tr = m_InvoiceLines.AddTr();
			Td[] td = new Td[4];
			td[0] = tr.AddTd(line.Label);
			td[1] = tr.AddTd("OK");
			td[2] = tr.AddTd(line.Price.ToString("0.00") + "€");
			td[3] = tr.AddTd();
			A removeLink = td[3].AddControl<A>();
			Img removeImg = removeLink.AddImg("X", "/Images/remove.png");
			Tr sepTr = m_InvoiceLines.AddTr();
			Td sepTd = sepTr.AddTd();

			td[1].Classes.Add("ok");
			td[2].Classes.Add("amount");
			td[3].Classes.Add("remove");
			removeLink.HRef = "/?command=removeLine&index=" + index;

			sepTr.Classes.Add("separator");
			sepTd.ColSpan = 4;

			return tr;
		}

		public override void ProcessHtmlRequest(Jayden.Dll.Web.HttpHandlerContext context)
		{

			base.ProcessHtmlRequest(context);
			ProcessRequestWithContext(context);
		}

		public void ProcessRequestWithContext(Jayden.Dll.Web.HttpHandlerContext context)
		{
			if (context.Request["command"] == "removeLine")
			{
				int lineIndex = int.Parse(context.Request["index"]);

				if (Page.Cart.Lines.Count > lineIndex)
				{
					Page.Cart.Lines.RemoveAt(lineIndex);
					if (context.Json != null)
					{
						string text = string.Format("{0} popjes", Page.Cart.Lines.Count);
						if (Page.Cart.Lines.Count == 1)
							text = "1 popje";
						context.Json.Add("itemCount", text);
						context.Json.Add("shipping", Page.Cart.ShippingCost.ToString("0.00") + "€");
						context.Json.Add("total", Page.Cart.Total.ToString("0.00") + "€");
						if(Page.Cart.Lines.Count != 0)
							context.Json.Add("summary", true);
					}
				}
			}

			m_InvoiceLines.Clear();

			int index = 0;
			foreach (CartSessionLine line in Page.Cart.Lines)
			{
				CreateCartLine(line, index);
				index++;
			}
			m_ShippingPrice.InnerText = Page.Cart.ShippingCost.ToString("0.00") + "€";
			m_TotalPrice.InnerText = Page.Cart.Total.ToString("0.00") + "€";

			if (Page.Cart.Lines.Count > 0)
				m_Summary.CssProperties.Add("display", "block");

			m_ItemCount.InnerText = string.Format("{0} popjes", Page.Cart.Lines.Count);
			if (Page.Cart.Lines.Count == 1)
				m_ItemCount.InnerText = "1 popje";
		}

		public override void ProcessJsonRequest(Jayden.Dll.Web.HttpHandlerContext context)
		{
			base.ProcessJsonRequest(context);
			ProcessRequestWithContext(context);
		}

		public override void ProcessJsRequest(Jayden.Dll.Web.HttpHandlerContext context)
		{
			base.ProcessJsRequest(context);

			context.Js["CartDiv"].AppendOnInit(@"
	var $invoice = $('#" + m_Invoice.Id + @"');
	var $invoiceLine = $('#" + m_InvoiceLines.Id + @"');
	var $shippingPrice = $('#" + m_ShippingPrice.Id + @"');
	var $totalPrice = $('#" + m_TotalPrice.Id + @"');
	var $warning = $('#" + m_Warning.Id + @"');
	var $itemCount = $('#" + m_ItemCount.Id + @"');
	var $summary = $('#" + m_Summary.Id + @"');

	var removeLine = function() {
		var $this = $(this);
		var $tr = $($this.parents('tr')[0]);
		var index = $tr[0].rowIndex;
		
		$invoice[0].deleteRow(index);
		$invoice[0].deleteRow(index);

		var lineIndex = parseInt((index - 1) / 2.0);

		return JAYDEN.sfn.submitAjaxData({
			format: 'json',
			command: 'removeLine',
			index: lineIndex
		}, '/cart.html', 'post');
	};

	JAYDEN.ajax.handlers.push({
		handle: function(data, textStatus, jqXHR) {
			if(data.summary)
				$summary.show();
			else
				$summary.hide();
			if(data.itemCount)
				$itemCount.text(data.itemCount);
			if(data.shipping)
				$shippingPrice.text(data.shipping);
			if(data.total)
				$totalPrice.text(data.total);
			if(data.warning)
				$warning.show();
			else
				$warning.hide();
		}
	});

	$invoiceLine.on('click', 'td.remove a', removeLine);
	
");
		}
	}
}